using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace PvpServer
{
    public class MatchService
    {
        HttpListener _httpListener = null;

        public void StartService(string url)
        {
            StartHttpServer(url);
        }

        public void StopService()
        {
            if (_httpListener != null)
                _httpListener.Stop();
        }

        async void StartHttpServer(string url)
        {
            var listener = new HttpListener();
            listener.Prefixes.Add(url);

            try
            {
                listener.Start();
            }
            catch (Exception e)
            {
                Logger.Log($"[MatchService.StartHttpServer]:@{url}      error={e}");
                return;
            }


            Logger.Log($"Http Server started on port {url}");

            while (true)
            {
                // 等待并处理请求
                HttpListenerContext context = await listener.GetContextAsync();
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;

                Logger.Log($"[MatchService.StartHttpServer.listener]:{request.Url}");

                // 处理请求的逻辑（例如返回一些数据）
                if (request.Url.AbsolutePath == "/match")
                {
                    await ProcessMatch(request, response);
                }
                else if (request.Url.AbsolutePath == "/queryHostReady")
                {
                    await ProcessQueryHostReady(request, response);
                }
                else if (request.Url.AbsolutePath == "/gameStart")
                {
                    await ProcessGameStart(request, response);
                }
                else if (request.Url.AbsolutePath == "/cancelMatch")
                {
                    await ProcessCancelMatch(request, response);
                }
                else if (request.Url.AbsolutePath == "/queryMatchState")
                {
                    await ProcessQueryMatchState(request, response);
                }
                else
                {
                    // 请求的路径无效，返回404
                    response.StatusCode = 404;
                    byte[] buffer = Encoding.UTF8.GetBytes("404 - Not Found");
                    await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
                }

                // 关闭响应流
                response.Close();
            }
        }

        private async Task ProcessQueryMatchState(HttpListenerRequest request, HttpListenerResponse response)
        {
            // 从POST请求体读取参数
            var requestData = await ReadRequestBodyAsync(request);
            var roomNum = requestData["roomNum"]?.ToString();
            var playerUID = requestData["uid"]?.ToString();

            var result = new JObject();
            var room = RoomService.Instance.GetRoomByRoomNum(roomNum);
            result["matchFinished"] = false;

            if (room != null)
            {
                if (room.MatchFinished && room.MatchPlayers.Contains(playerUID))
                {
                    result["roomNum"] = room.RoomNum;
                    result["matchFinished"] = room.MatchFinished;
                    result["uri"] = room.Uri;
                    result["port"] = room.Port;
                    result["maxPlayerCount"] = room.MaxPlayerCount;
                    result["roomOwner"] = room.RoomOwnerUID == playerUID;
                    result["players"] = new JArray(room.MatchPlayers.ToList());
                }
            }

            byte[] buffer = Encoding.UTF8.GetBytes(result.ToString());

            // 设置响应头
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength64 = buffer.Length;

            // 返回数据
            await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
        }

        // 添加读取POST请求体的辅助方法
        private async Task<JObject> ReadRequestBodyAsync(HttpListenerRequest request)
        {
            if (!request.HasEntityBody)
            {
                return new JObject();
            }

            using (var reader = new System.IO.StreamReader(request.InputStream, request.ContentEncoding))
            {
                string body = await reader.ReadToEndAsync();
                try
                {
                    return JObject.Parse(body);
                }
                catch
                {
                    return new JObject();
                }
            }
        }

        private async Task ProcessQueryHostReady(HttpListenerRequest request, HttpListenerResponse response)
        {
            // 从POST请求体读取参数
            var requestData = await ReadRequestBodyAsync(request);
            var roomNum = requestData["roomNum"]?.ToString();

            var result = new JObject();
            var room = RoomService.Instance.GetRoomByRoomNum(roomNum);
            if (room != null)
            {
                result["hostReady"] = room.HostReady;
            }
            else
            {
                result["hostReady"] = false;
            }

            byte[] buffer = Encoding.UTF8.GetBytes(result.ToString());

            // 设置响应头
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength64 = buffer.Length;

            // 返回数据
            await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
        }

        async Task ProcessMatch(HttpListenerRequest request, HttpListenerResponse response)
        {
            // 从POST请求体读取参数
            var requestData = await ReadRequestBodyAsync(request);
            var maxPlayerCount = requestData["maxPlayerCount"]?.ToObject<int>() ?? 2; // 默认值为2
            var playerUID = requestData["uid"]?.ToString();
            if (string.IsNullOrEmpty(playerUID))
            {
                return;
            }

            //返回一个房间的信息
            var (room, newRoom) = RoomService.Instance.GetRoom(maxPlayerCount);
            room.AddMatchPlayer(playerUID);

            var result = new JObject();
            result["roomNum"] = room.RoomNum;
            Logger.Log($"匹配成功，发送房间信息:{room.Port}");
            byte[] buffer = Encoding.UTF8.GetBytes(result.ToString());

            // 设置响应头
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength64 = buffer.Length;

            // 返回数据
            await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
        }

        async Task ProcessCancelMatch(HttpListenerRequest request, HttpListenerResponse response)
        {
            // 从POST请求体读取参数
            var requestData = await ReadRequestBodyAsync(request);
            var playerUID = requestData["uid"]?.ToString();
            if (string.IsNullOrEmpty(playerUID))
            {
                return;
            }

            var room = RoomService.Instance.GetRoomByPlayerUID(playerUID);
            if (room != null)
            {
                room.RemoveMatchPlayer(playerUID);
                Logger.Log($"取消匹配：room:{room.RoomNum},uid:{playerUID}");
            }

            var result = new JObject();
            result["success"] = true;
            byte[] buffer = Encoding.UTF8.GetBytes(result.ToString());

            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength64 = buffer.Length;
            await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
        }

        async Task ProcessGameStart(HttpListenerRequest request, HttpListenerResponse response)
        {
            // 从POST请求体读取参数
            var requestData = await ReadRequestBodyAsync(request);
            var roomNum = requestData["roomNum"]?.ToString();

            var room = RoomService.Instance.GetRoomByRoomNum(roomNum);
            if (room != null)
            {
                room.Gaming = true;
                Logger.Log($"房间开始游戏：{room.RoomNum}");
            }

            // 返回成功响应
            var result = new JObject();
            result["success"] = true;
            byte[] buffer = Encoding.UTF8.GetBytes(result.ToString());

            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.ContentLength64 = buffer.Length;
            await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
        }
    }
}